﻿/*
    Copyright (c) 2012, iD Commerce + Logistics
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted
    provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this list of conditions
    and the following disclaimer. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the documentation and/or other
    materials provided with the distribution.
 
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
    OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Reactive;
using System.Reactive.Threading.Tasks;

namespace IdComLog.Reactive
{
    /// <summary>
    /// Provides utility methods for working with the filesystem.
    /// </summary>
    public static class FileSystem
    {
        static readonly TimeSpan SafeCheckPeriod = TimeSpan.FromSeconds(30.0);

        /// <summary>
        /// Watches a filesystem for changes.
        /// </summary>
        /// <param name="path">The path to watch.</param>
        /// <param name="filter">A wildcard filter.</param>
        /// <param name="notifyOnChanged">If true, a notification will be sent if a file was changed.</param>
        /// <param name="notifyOnCreated">If true, a notification will be sent if a file was created.</param>
        /// <param name="notifyOnDeleted">If true, a notification will be sent if a file was deleted.</param>
        /// <param name="notifyOnRenamed">If true, a notification will be sent if a file was renamed.</param>
        /// <param name="includeSubdirectories">If true, will watch subdirectories as well.</param>
        /// <returns>A cold observable which watches a filesystem path.</returns>
        /// <remarks>
        /// This uses FileSystemWatcher internally, which is pretty brittle when it
        /// comes to common OS issues -- errors *will* occur, and FSW can easily lose
        /// track of its target.
        /// 
        /// To combat this, the path will be periodically checked to ensure nothing
        /// has occurred which might cause this.
        /// 
        /// Additionally, a null FileSystemEventArgs will be pushed once monitoring
        /// has started. Applications should use this to manually check the filesystem
        /// in a way which ensures any pre-monitoring changes will be found.
        /// 
        /// Proper usage is to Catch().Retry() and look for unfound changes when a null
        /// is found.
        /// </remarks>
        public static IObservable<FileSystemEventArgs> Watch(string path, string filter = null, bool notifyOnChanged = false, bool notifyOnCreated = false, bool notifyOnDeleted = false, bool notifyOnRenamed = false, bool includeSubdirectories = false)
        {
            Contract.Requires(path != null);
            Contract.Ensures(Contract.Result<IObservable<FileSystemEventArgs>>() != null);

            if (!notifyOnChanged && !notifyOnCreated && !notifyOnDeleted && !notifyOnRenamed)
            {
                return Observable.Empty<FileSystemEventArgs>();
            }

            return Observable.Using(() => new FileSystemWatcher(), fsw =>
            {
                fsw.Path = path;
                fsw.Filter = filter;
                fsw.IncludeSubdirectories = includeSubdirectories;

                List<IObservable<FileSystemEventArgs>> fsos = new List<IObservable<FileSystemEventArgs>>();

                if (notifyOnChanged || notifyOnCreated || notifyOnDeleted)
                {
                    fsos.Add(Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>(a => ((FileSystemEventHandler)((s, ea) => a(ea))),
                        eh =>
                        {
                            if (notifyOnChanged) fsw.Changed += eh;
                            if (notifyOnCreated) fsw.Created += eh;
                            if (notifyOnDeleted) fsw.Deleted += eh;
                        },
                        eh =>
                        {
                            if (notifyOnChanged) fsw.Changed -= eh;
                            if (notifyOnCreated) fsw.Created -= eh;
                            if (notifyOnDeleted) fsw.Deleted -= eh;
                        }));
                }

                if (notifyOnRenamed)
                {
                    fsos.Add(Observable.FromEvent<RenamedEventHandler, FileSystemEventArgs>(a => ((RenamedEventHandler)((s, ea) => a(ea))),
                        reh => fsw.Renamed += reh,
                        reh => fsw.Renamed -= reh));
                }

                fsos.Add(Observable.FromEvent<ErrorEventHandler, Exception>(a => ((ErrorEventHandler)((s, ea) => a(ea.GetException()))),
                    eeh => fsw.Error += eeh,
                    eeh => fsw.Error -= eeh).SelectMany(x => Observable.Throw<FileSystemEventArgs>(x)));

                fsos.Add(Observable.Defer(() =>
                {
                    fsw.EnableRaisingEvents = true;
                    return Observable.Return<FileSystemEventArgs>(null);
                }));

                DateTime modifyDate = DateTime.MaxValue;
                DirectoryInfo directoryInfo = new DirectoryInfo(path);

                Func<IObservable<bool>> refresh = Observable.ToAsync<bool>(() =>
                {
                    directoryInfo.Refresh();

                    if (!directoryInfo.Exists)
                    {
                        return false;
                    }

                    if (directoryInfo.CreationTimeUtc > modifyDate)
                    {
                        return false;
                    }

                    modifyDate = directoryInfo.CreationTimeUtc;
                    return true;
                });

                fsos.Add(Observable.Timer(TimeSpan.Zero, SafeCheckPeriod)
                    .SelectMany(x => refresh())
                    .SelectMany(x =>
                    {
                        if (!x)
                        {
                            return Observable.Throw<FileSystemEventArgs>(new DirectoryNotFoundException());
                        }

                        return Observable.Empty<FileSystemEventArgs>();
                    }));

                return fsos.Merge();
            });
        }

        /// <summary>
        /// Watches a filesystem for new or existing files.
        /// </summary>
        /// <param name="path">The path to watch.</param>
        /// <param name="filter">A wildcard filter.</param>
        /// <returns>A cold observable which watches a filesystem path.</returns>
        public static IObservable<string> FindWatch(string path, string filter = null)
        {
            Contract.Requires(path != null);
            Contract.Ensures(Contract.Result<IObservable<string>>() != null);

            path = Path.GetFullPath(path);

            return IdComLog.Reactive.FileSystem.Watch(path, filter, notifyOnCreated: true)
                .SelectMany(x =>
                    x != null ? new[] { x.FullPath } :
                    filter != null ? Directory.EnumerateFiles(path, filter) :
                    Directory.EnumerateFiles(path));
        }

        /// <summary>
        /// Delays paths until they become unlocked.
        /// </summary>
        /// <param name="paths">The paths to delay.</param>
        /// <returns>A cold observable.</returns>
        public static IObservable<string> WaitForPathUnlock(this IObservable<string> paths)
        {
            return paths
                .Select(x => Observable.FromAsync(ct => FileEx.WaitForUnlock(x, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, ct)).Select(y => x))
                .Concat();
        }
    }
}
